const gulp = require('gulp'); // 引入 gulp
const minifycss = require('gulp-minify-css'); // 引入 gulp-uglify 插件
const uglify = require('gulp-uglify');
const clean = require('gulp-clean');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const magicImporter = require('node-sass-magic-importer');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const rename = require('gulp-rename');
const through2 = require('through2');
const minimist = require('minimist');
const fs = require('fs');

/** *****************************
    farris icon 图标库文件  ******开始******
*******************************/

gulp.task('farrisicon-css', (param) => {
    return gulp
        .src('packages/farris-theme/farris-icon/entrance/farrisicon.scss')
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(minifycss())
        .pipe(gulp.dest('packages/farris-theme/farris-icon/dist/'));
});

gulp.task('farrisicon-ttf', () => {
    return gulp
        .src([
            'packages/farris-theme/farris-icon/scss/extend/farrisicon-extend.ttf',
            'packages/farris-theme/farris-icon/scss/farris/farrisicon.ttf',
            'packages/farris-theme/farris-icon/entrance/farrisicon.html'
        ])
        .pipe(gulp.dest('packages/farris-theme/farris-icon/dist'));
});

gulp.task('copy-font-to-assets', () => {
    return gulp
        .src([
            'packages/farris-theme/farris-icon/scss/extend/farrisicon-extend.ttf',
            'packages/farris-theme/farris-icon/scss/farris/farrisicon.ttf'
        ])
        .pipe(gulp.dest('packages/farris-theme/theme/assets'));
});

gulp.task('farrisicon-publish', () => {
    return gulp
        .src(['packages/farris-theme/farris-icon/package.json', 'farris-icon/README.md'])
        .pipe(gulp.dest('packages/farris-theme/farris-icon/dist'));
});

gulp.task('farrisicon-clean', () => {
    return gulp.src(['packages/farris-theme/farris-icon/dist/*']).pipe(clean({ force: true }));
});

// 生成样式
gulp.task('farrisicon', gulp.series('farrisicon-clean', 'farrisicon-css', 'farrisicon-ttf', 'copy-font-to-assets'));
// 发布
gulp.task(
    'farrisicon:publish',
    gulp.series('farrisicon-clean', 'farrisicon-css', 'farrisicon-ttf', 'farrisicon-publish', 'copy-font-to-assets')
);
/** *****************************
    farris icon 图标库文件  ******结束******
*******************************/

/** *****************************
    Farris 主题样式生成  ******开始******
*******************************/
// 定义主题
let themeDetail = {};

/** 控制参数 ******开始******/
let srcDir = 'packages/farris-theme/theme/entrance/';
let distDir = 'packages/farris-theme/theme/dist';
const argvDirIndex = process.argv.indexOf('--dir');
if (argvDirIndex > -1) {
    srcDir = process.argv[argvDirIndex + 1];
    distDir = srcDir + 'dist';
}
// 用于格式化命令参数
const knownOptions = {
    default: {
        code: 'default',
        type: 'default'
    }
};

/** *****************************
如果命令是 gulp theme --code default --type default
process.argv:[node路径,gulp路径,'theme','--code','default','--type','default']
process.argv.slice(2): 执行结果是 ['theme','--code','default','--type','default']
minimist:执行结果{_:['theme'],code:'default','type':'default'}
*******************************/

const options = minimist(process.argv.slice(2), knownOptions);
const baseThemes = 'packages/farris-theme/themes/';
/** 控制参数 ******结束******/

// 修改内容
function modifyContent(detailFunc) {
    return through2.obj(function (chunk, encoding, done) {
        detailFunc(chunk);
        this.push(chunk);
        done();
    });
}

function findThemeSetting(themeName, themes) {
    const findTheme = themes.find((item) => item.theme === themeName);
    return findTheme;
}

// 读取配置文件，更新当前主题
gulp.task('getthemes', () => {
    return gulp.src('packages/farris-theme/themes/setting.json').pipe(
        modifyContent((file) => {
            const themes = JSON.parse(file.contents);
            themeDetail = findThemeSetting(options.code, themes);
            distDir = themeDetail.dist + '/' + options.type;
        })
    );
});

// 清空
gulp.task('clean', () => {
    return gulp.src([distDir + '/*.css']).pipe(clean({ force: true }));
});
function modifySCSS(chunk) {
    let content = String(chunk.contents);
    const themePath = baseThemes + options.code + '/' + options.type + '/';
    // 追加变量定义
    if (fs.existsSync(themePath + 'index.scss')) {
        content = "@import '" + themePath + "index.scss';\r\n" + content;
    }
    // 追加扩展定义
    if (chunk.history[0].indexOf('farris-default.scss') > -1) {
        if (fs.existsSync(themePath + 'extend.scss')) {
            content += "@import '" + themePath + "extend.scss';\r\n";
        }
    }
    chunk.contents = Buffer.from(content);
}

/* iteration ***********************************************开始****************************/
gulp.task('iteration', (param) => {
    return gulp
        .src(srcDir + 'iteration.scss')
        .pipe(modifyContent(modifySCSS))
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(autoprefixer())
        .pipe(minifycss())
        .pipe(gulp.dest('packages/farris-theme/' + distDir));
});
/*  iteration***********************************************结束****************************/

/* farris 自定义样式 相关 ******开始******/
gulp.task('farris-css', () => {
    return gulp
        .src([srcDir + 'farris-iteration-b.scss', srcDir + 'farris-default.scss'])
        .pipe(modifyContent(modifySCSS))
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(autoprefixer())
        .pipe(gulp.dest('packages/farris-theme/' + distDir + '/temp'));
});

gulp.task('farris-concat', () => {
    return gulp
        .src([
            'packages/farris-theme/' + distDir + '/temp/farris-iteration-b.css',
            'packages/farris-theme/' + distDir + '/temp/farris-default.css'
        ])
        .pipe(concat('farris-default.css'))
        .pipe(minifycss())
        .pipe(gulp.dest('packages/farris-theme/' + distDir));
});
gulp.task('farris-clean', () => {
    return gulp.src(['packages/farris-theme/' + distDir + '/temp']).pipe(clean({ force: true }));
});
gulp.task('farris', gulp.series('farris-css', 'farris-concat', 'farris-clean'));

/* farris 自定义样式 相关 ******结束******/

gulp.task('all:concat', () => {
    return gulp
        .src([
            'packages/farris-theme/' + distDir + '/iteration.css',
            'packages/farris-theme/farris-icon/dist/farrisicon.css',
            'packages/farris-theme/' + distDir + '/farris-default.css'
        ])
        .pipe(concat('farris-all.css'))
        .pipe(gulp.dest('packages/farris-theme/' + distDir));
});

/** * 生成farris未压缩版样式 **/
gulp.task('all', gulp.series('clean', 'iteration', 'farris', 'farrisicon', 'all:concat'));

// 更新资源
gulp.task('update-theme-assets', () => {
    const themePath = baseThemes + options.code + '/';
    return gulp
        .src(['packages/farris-theme/theme/assets/**/*', themePath + 'assets/**/*'])
        .pipe(gulp.dest('packages/farris-theme/' + distDir));
});

gulp.task('theme', gulp.series('getthemes', 'all', 'update-theme-assets'));

/** *****************************
    Farris 主题样式生成  ******结束******
*******************************/

/** *****************************
      Farris 公共样式生成 ******开始******
*******************************/
const pubOptions = minimist(process.argv.slice(2), { default: { code: 'default' } });
let pubDistDir = '';
const pubSrcDir = 'packages/farris-theme/farris-pub/public/';
// 更新
gulp.task('pubGetSetting', () => {
    return gulp.src(pubSrcDir + 'setting.json').pipe(
        modifyContent((file) => {
            const themes = JSON.parse(file.contents);
            themeDetail = findThemeSetting(pubOptions.code, themes);
            pubDistDir = themeDetail.dist;
        })
    );
});

function modifyPubSCSS(chunk) {
    let content = String(chunk.contents);
    const themePath = pubSrcDir + 'themes/' + pubOptions.code + '/';
    // 追加变量定义
    if (fs.existsSync(themePath + '_index.scss')) {
        content = content.replace('//@theme', "@import './themes/" + pubOptions.code + "/index.scss';\r\n");
    }
    chunk.contents = Buffer.from(content);
}

// 生成文件
gulp.task('pubMain', () => {
    return gulp
        .src(pubSrcDir + 'farris-pub.scss')
        .pipe(modifyContent(modifyPubSCSS))
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(autoprefixer())
        .pipe(minifycss())
        .pipe(gulp.dest('packages/farris-theme/' + pubDistDir));
});

// 生成公共样式
gulp.task('pubcss', gulp.series('pubGetSetting', 'pubMain'));

const pubSiteSrc = 'packages/farris-theme/farris-pub/site/';
const pubDocsSrc = 'packages/farris-theme/farris-pub/docs/';
const pubDocsDist = 'packages/farris-theme/dist/farris-pub/';
// 文档样式
gulp.task('pubdocs', (param) => {
    return gulp
        .src([pubDocsSrc + 'docs.scss', pubDocsSrc + 'light.scss'])
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(autoprefixer())
        .pipe(concat('docs.css'))
        .pipe(minifycss())
        .pipe(gulp.dest(pubDocsDist + 'css/'));
});

gulp.task('pubsiteCopy', () => {
    return gulp.src([pubSiteSrc + '**/*']).pipe(gulp.dest(pubDocsDist));
});
gulp.task('pubsiteMinJS', () => {
    return gulp
        .src([pubSiteSrc + 'js/*'])
        .pipe(uglify())
        .pipe(gulp.dest(pubDocsDist + 'js'));
});
gulp.task('pubsiteSettings', () => {
    return gulp
        .src(['packages/farris-theme/farris-pub/package.json', 'packages/farris-theme/farris-pub/README.md'])
        .pipe(gulp.dest(pubDocsDist));
});

gulp.task('pubsite', gulp.series('pubcss', 'pubdocs', 'pubsiteCopy'));
// 增加了 js压缩、配置文件
gulp.task('pubsite:publish', gulp.series('pubcss', 'pubdocs', 'pubsiteCopy', 'pubsiteMinJS', 'pubsiteSettings'));
/** *****************************
      Farris 公共样式生成 ******结束******
*******************************/

/**
 *  用于验证scss生成文件-----可直接拷贝运行*/
gulp.task('to-css', (param) => {
    return gulp
        .src('packages/farris-theme/scss-to-css/test.scss')
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(autoprefixer())
        .pipe(gulp.dest('scss-to-css'));
});

/** *****************************
     整个工程的样式 ******开始******
*******************************/

gulp.task('docs', (param) => {
    return gulp
        .src('packages/farris-theme/docs/scss/docs.scss')
        .pipe(sourcemaps.init())
        .pipe(
            sass({
                importer: magicImporter(),
                'output-style': 'expanded',
                precision: 5
            }).on('error', sass.logError)
        )
        .pipe(sourcemaps.write({ includeContent: false }))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(autoprefixer())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('packages/farris-theme/src/assets/docs'));
});
/** *****************************
     整个工程的样式  ******结束******
*******************************/
